package org.jeecg.modules.flower.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.flower.service.IFlowerOutorderinfoService;
import org.jeecg.modules.flower.service.IFlowerTagInfoService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecg.modules.flower.vo.FlowerAfSalesMainPage;
import org.jeecg.modules.flower.vo.FlowerOutorderPage;
import org.jeecg.modules.flowerutil.PeriodUtils;
import org.jeecg.modules.flowerutil.controller.PeriodController;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.def.TemplateExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecgframework.poi.excel.view.JeecgTemplateExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

//会影响的操作====：
//出库主表： 删除，-----编辑不会影响
//出库子表：
//        新增
//        修改
//        删除


/**
 * @Description: 出库单表
 * @Author: jeecg-boot
 * @Date: 2022-06-09
 * @Version: V1.0
 */
@Api(tags = "出库单主表")
@RestController
@RequestMapping("/flower/flowerOutorder")
@Slf4j
public class FlowerOutorderController extends JeecgController<FlowerOutorder, IFlowerOutorderService> {
    @Autowired
    private IFlowerOutorderService flowerOutorderService;
    @Autowired
    private IFlowerCostService flowerCostService;
    @Autowired
    private IFlowerTagInfoService flowerTagInfoService;
    @Autowired
    private IFlowerOutorderinfoService flowerOutorderinfoService;
    @Autowired
    private IFlowerOutorderinfoDService flowerOutorderinfoDService;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IFlowerAfSalesMainService flowerAfSalesMainService;
    @Autowired
    private IFlowerAfSalesDetalService flowerAfSalesDetalService;
    @Autowired
    private IFlowerStorehouseService flowerStorehouseService;
    @Autowired
    private XsglService xsglService;

    @Autowired
    private IFlowerSettleAccountsService settleAccountsService;

    @Value("${yth.tempExcelOrder}")
    private String tempExcelOrder;

    @Value("${yth.tempExcelOut}")
    private String tempExcelOut;

    @Autowired
    @Lazy
    private RedisUtil redisUtil;



    /**
     * 分页列表查询
     *
     * @param flowerOutorder
     * @param pageNo
     * @param pageSize
     * @param sDate
     * @param eDate
     * @param req
     * @return
     */
    @AutoLog(value = "出库单表-分页列表查询")
    @ApiOperation(value = "出库单表-分页列表查询", notes = "出库单表-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "flower/FlowerOutorderList")
    public Result<?> queryPageList(FlowerOutorder flowerOutorder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(value = "sDate", defaultValue = "") String sDate,
                                   @RequestParam(value = "eDate", defaultValue = "") String eDate,
                                   @RequestParam(value = "jsDate", defaultValue = "") String jsDate,
                                   @RequestParam(value = "jeDate", defaultValue = "") String jeDate,
                                   @RequestParam(value = "topresDate", defaultValue = "") String topresDate,
                                   @RequestParam(value = "topreeDate", defaultValue = "") String topreeDate,
                                   @RequestParam(value = "appOrderNo",defaultValue = "",required = false) String appOrderNo,
                                   HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        QueryWrapper<FlowerOutorder> queryWrapper = new QueryWrapper<>();
        Page<FlowerOutorder> page = new Page<FlowerOutorder>(pageNo, pageSize);
        if (StringUtils.isNotBlank(appOrderNo)) {//app搜索使用
            queryWrapper.and(wq ->  wq.like("order_no" , appOrderNo).or().like("user" , appOrderNo).or().like("touser" , appOrderNo)  );
        }
        if (StringUtils.isNotBlank(flowerOutorder.getOrderNo())) {
            queryWrapper.like("order_no" , flowerOutorder.getOrderNo());
        }
        if (StringUtils.isNotBlank(flowerOutorder.getSource())) {
            queryWrapper.eq("source" , flowerOutorder.getSource());
        }
        if ( flowerOutorder.getState()!=null) {
            queryWrapper.eq("state" , flowerOutorder.getState());
        }
        if (StringUtils.isNotBlank(flowerOutorder.getBusinessPerson())) {
            queryWrapper.like( "business_person" , flowerOutorder.getBusinessPerson());
        }
        if (StringUtils.isNotBlank(flowerOutorder.getUser())) {
            queryWrapper.like( "user" , flowerOutorder.getUser());
        }
        if (StringUtils.isNotBlank(flowerOutorder.getTouser())) {
            queryWrapper.like( "touser" , flowerOutorder.getTouser());
        }
        if ( StringUtils.isNotBlank(flowerOutorder.getCreateBy()) ) {
            queryWrapper.eq("create_by" , flowerOutorder.getCreateBy());
        }
        if (StringUtils.isNotBlank(sDate)) {
            queryWrapper.ge( "stock_in_time", sDate);
        }
        if (StringUtils.isNotBlank(eDate)) {
            queryWrapper.le("stock_in_time", eDate + " 23:59:59");
        }
        if (StringUtils.isNotBlank(jsDate)) {
            queryWrapper.ge("surepipetime" , jsDate);
        }
        if (StringUtils.isNotBlank(jeDate)) {
            queryWrapper.le("surepipetime", jeDate + " 23:59:59");
        }
        if (StringUtils.isNotBlank(topresDate)) {
            queryWrapper.ge("topresstime" , topresDate);
        }
        if (StringUtils.isNotBlank(topreeDate)) {
            queryWrapper.le( "topresstime", topreeDate + " 23:59:59");
        }
        queryWrapper.orderByDesc( "order_no" ,"stock_in_time" ,"create_time");
        queryWrapper.inSql("id" ,"SELECT a.order_id FROM t_flower_outorderinfo a LEFT JOIN   flower_storehouse b  on   a.storehouse = b.code  " +
                "LEFT JOIN   flower_storehouse_detail c  on b.id =c.mainid WHERE  personid = '" + sysUser.getId() + "'");
        QueryGenerator.installAuthMplus(queryWrapper,FlowerOutorder.class);
        IPage<FlowerOutorder> pageList = flowerOutorderService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param flowerOutorderPage
     * @return
     */
    @AutoLog(value = "出库单表-添加")
    @ApiOperation(value = "出库单表-添加", notes = "出库单表-添加")
    @PostMapping(value = "/add")
    public synchronized Result<?> add(@RequestBody FlowerOutorderPage flowerOutorderPage) throws IOException {
        FlowerOutorder flowerOutorder = new FlowerOutorder();
        BeanUtils.copyProperties(flowerOutorderPage, flowerOutorder);
        String  rest = flowerOutorderService.saveMain(flowerOutorder, flowerOutorderPage.getFlowerOutorderinfoList());
        return Result.ok(rest);
    }

    /**
     * 编辑
     *
     * @param flowerOutorderPage
     * @return
     */
    @AutoLog(value = "出库单表-编辑")
    @ApiOperation(value = "出库单表-编辑", notes = "出库单表-编辑")
    @PutMapping(value = "/edit")
    @Transactional
    public Result<?> edit(@RequestBody FlowerOutorderPage flowerOutorderPage) throws IOException {
//        flowerOutorderService.updateById(flowerOutorder);
        FlowerOutorder flowerOutorder = new FlowerOutorder();
        BeanUtils.copyProperties(flowerOutorderPage, flowerOutorder);
        FlowerOutorder flowerOutorderEntity = flowerOutorderService.getById(flowerOutorder.getId());
        String source = flowerOutorderEntity.getSource();
        if (flowerOutorderEntity == null) {
            return Result.error("未找到对应数据");
        }
        Integer state = flowerOutorderEntity.getState();
        if ( state.compareTo(1)== 0 && "手动出库".equals(source)) {
            return Result.error("请先取消预收资金确认");
        }else if ( state.compareTo(0)== 0) {
            return Result.error("请先取消确认出库");
        }else if ( state.compareTo(2)== 0) {
            return Result.error("请先取消运管确认");
        }else if ( state.compareTo(3)== 0) {
            return Result.error("请先撤销提交审核");
        }
        boolean accountState = settleAccountsService.getAccountState(flowerOutorderPage.getPeriod());
        if(!accountState){
            throw new RuntimeException("已结账的单据不可编辑！") ;
        }

        //查询是否存在已出库数据，如果存在，则不允许编辑，请先撤销出库
        List<FlowerTagInfo> taginfoList = flowerOutorderService.getTaginfoByOutoerderID("'" + flowerOutorderPage.getId() + "'");
        for (FlowerTagInfo tagInfo : taginfoList) {
            if ("2".equals(tagInfo.getState())) {
                log.error("存在已出库的数据，无法删除，出库id：" + flowerOutorderPage.getId());
                throw new RuntimeException("存在已出库的数据，请先撤销出库！");
            }
        }
        BigDecimal sumNumber =  new BigDecimal("0");
        BigDecimal sumMoney = new BigDecimal("0");
        for (FlowerOutorderinfo flowerOutorderinfo : flowerOutorderPage.getFlowerOutorderinfoList()) {
            BigDecimal number = flowerOutorderinfo.getNumber();
            sumNumber = sumNumber.add( number );
            sumMoney = sumMoney.add(flowerOutorderinfo.getTotalprice());
        }
        flowerOutorder.setNumber( sumNumber );
        flowerOutorder.setTotalprice(sumMoney);
        flowerOutorderService.updateMain(flowerOutorder, flowerOutorderPage.getFlowerOutorderinfoList());
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单表-通过id删除")
    @ApiOperation(value = "出库单表-通过id删除(真实删除)", notes = "出库单表-通过id删除")
    @DeleteMapping(value = "/delete")
    @Transactional
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
//        LambdaQueryWrapper<FlowerOutorderinfo> orderinfoQuery = new LambdaQueryWrapper<>();
//        orderinfoQuery.eq(FlowerOutorderinfo::getOrderId, id);
//        flowerOutorderinfoService.remove(orderinfoQuery);//删除子表
//        flowerOutorderService.removeById(id);//删除主表

        //先查询是否存在已经出库的
        //。。。。。。。。。。。。。
        List<FlowerTagInfo> taginfoList = flowerOutorderService.getTaginfoByOutoerderID("'" + id + "'");
        for (FlowerTagInfo tagInfo : taginfoList) {
            if ("2".equals(tagInfo.getState())) {
                log.error("存在已出库的数据，无法删除，出库id：" + id);
                throw new RuntimeException("存在已出库的数据，请先撤销出库！");
            }
        }
        FlowerOutorder flowerOutorder = flowerOutorderService.getById(id);
        if(flowerOutorder.getState().compareTo(-1)!= 0){
            throw new RuntimeException("只有待出库状态才能删除，请先撤销确认！");
        }
        //2、删除主子表
        flowerOutorderService.delMain(id);
        return Result.ok("删除成功!");
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "出库单主表-批量删除")
    @ApiOperation(value = "出库单主表-批量删除", notes = "出库单主表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        //查找是否存在已经出库的，存在则不允许删除
        //1、查找是否存在已经出库的
        String[] split = ids.split(",");
        String idsList = "";
        for (String id : split) {
            FlowerOutorder flowerOutorder = flowerOutorderService.getById(id);
            if(flowerOutorder.getState()!= -1){
                throw new RuntimeException("只有待出库状态才能删除，请先撤销确认！");
            }
            if (StringUtils.isBlank(idsList) || idsList.isEmpty()) {
                idsList = "'" + id + "'";
            } else {
                idsList += ",'" + id + "'";
            }
        }
        List<FlowerTagInfo> taginfoList = flowerOutorderService.getTaginfoByOutoerderID(idsList);
        for (FlowerTagInfo tagInfo : taginfoList) {
            if ("2".equals(tagInfo.getState())) {
                log.error("存在已出库的数据，无法删除，出库id：" + ids);
                throw new RuntimeException("存在已出库的数据，请联系管理员！");
            }
        }
        this.flowerOutorderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单表-通过id查询")
    @ApiOperation(value = "出库单表-通过id查询", notes = "出库单表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        FlowerOutorder flowerOutorder = flowerOutorderService.getById(id);
        if (flowerOutorder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(flowerOutorder);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单子表通过主表ID查询")
    @ApiOperation(value = "出库单子表主表ID查询", notes = "出库单子表-通主表ID查询")
    @GetMapping(value = "/queryFlowerOutorderinfoByMainId")
    public Result<?> queryFlowerOutorderinfoListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<FlowerOutorderinfo> flowerOutorderinfoList = flowerOutorderinfoService.selectByMainId(id);
        return Result.ok(flowerOutorderinfoList);
    }
    /**
     * 导出excel
     *
     * @param request
     * @param flowerOutorder
     */
    @RequestMapping(value = "/exportXlsAll")
    @PermissionData(pageComponent = "flower/FlowerOutorderList")
    @ApiOperation(value = "全部导出-按时间段导出", notes = "全部导出-按时间段导出")
    public ModelAndView exportXlsAll(HttpServletRequest request, FlowerOutorder flowerOutorder,
                                     @RequestParam(value = "sDate", defaultValue = "") String sDate,
                                     @RequestParam(value = "eDate", defaultValue = "") String eDate,
                                   @RequestParam(value = "jsDate", defaultValue = "") String jsDate,
                                     @RequestParam(value = "jeDate", defaultValue = "") String jeDate,
                                   @RequestParam(value = "topresDate", defaultValue = "") String topresDate,
                                     @RequestParam(value = "topreeDate", defaultValue = "") String topreeDate,
                                     @RequestParam(value = "appOrderNo", defaultValue = "") String appOrderNo) {
        // Step.1 组装查询条件查询数据
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        QueryWrapper<FlowerOutorder> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(appOrderNo)) {//app搜索使用
            queryWrapper.and(wq ->  wq.like("order_no" , appOrderNo).or().like("user" , appOrderNo).or().like("touser" , appOrderNo)  );
        }
        if (StringUtils.isNotBlank(flowerOutorder.getOrderNo())) {
            queryWrapper.like("order_no" , flowerOutorder.getOrderNo());
        }
        if (StringUtils.isNotBlank(flowerOutorder.getSource())) {
            queryWrapper.eq("source" , flowerOutorder.getSource());
        }
        if ( flowerOutorder.getState()!=null) {
            queryWrapper.eq("state" , flowerOutorder.getState());
        }
        if (StringUtils.isNotBlank(flowerOutorder.getBusinessPerson())) {
            queryWrapper.like( "business_person" , flowerOutorder.getBusinessPerson());
        }
        if (StringUtils.isNotBlank(flowerOutorder.getUser())) {
            queryWrapper.like( "user" , flowerOutorder.getUser());
        }
        if (StringUtils.isNotBlank(flowerOutorder.getTouser())) {
            queryWrapper.like( "touser" , flowerOutorder.getTouser());
        }
        if ( StringUtils.isNotBlank(flowerOutorder.getCreateBy()) ) {
            queryWrapper.eq("create_by" , flowerOutorder.getCreateBy());
        }
        if (StringUtils.isNotBlank(sDate)) {
            queryWrapper.ge( "stock_in_time", sDate);
        }
        if (StringUtils.isNotBlank(eDate)) {
            queryWrapper.le("stock_in_time", eDate + " 23:59:59");
        }
        if (StringUtils.isNotBlank(jsDate)) {
            queryWrapper.ge("surepipetime" , jsDate);
        }
        if (StringUtils.isNotBlank(jeDate)) {
            queryWrapper.le("surepipetime", jeDate + " 23:59:59");
        }
        if (StringUtils.isNotBlank(topresDate)) {
            queryWrapper.ge("topresstime" , topresDate);
        }
        if (StringUtils.isNotBlank(topreeDate)) {
            queryWrapper.le( "topresstime", topreeDate + " 23:59:59");
        }
        queryWrapper.orderByAsc( "stock_in_time" ,"create_time");
        queryWrapper.inSql("id","SELECT a.order_id FROM t_flower_outorderinfo a LEFT JOIN   flower_storehouse b  on   a.storehouse = b.code " +
                "LEFT JOIN   flower_storehouse_detail c  on b.id =c.mainid WHERE  personid = '" + sysUser.getId() + "'");

        QueryGenerator.installAuthMplus(queryWrapper,FlowerOutorder.class);
        //Step.2 获取导出数据
        List<FlowerOutorder> queryList = flowerOutorderService.list(queryWrapper);

        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<FlowerOutorder> flowerOutorderList = new ArrayList<FlowerOutorder>();
        if (oConvertUtils.isEmpty(selections)) {
            flowerOutorderList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            flowerOutorderList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<FlowerOutorderPage> pageList = new ArrayList<FlowerOutorderPage>();
        for (FlowerOutorder main : flowerOutorderList) {
            FlowerOutorderPage vo = new FlowerOutorderPage();
            BeanUtils.copyProperties(main, vo);
            List<FlowerOutorderinfo> flowerOutorderinfoList = flowerOutorderinfoService.selectByMainId(main.getId());
            for(FlowerOutorderinfo flowerOutorderinfo :flowerOutorderinfoList){
                if(StringUtils.isBlank(flowerOutorderinfo.getStorehouse())){
                    LambdaQueryWrapper<FlowerOutorderinfoD> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(FlowerOutorderinfoD::getMainid,flowerOutorderinfo.getId());
                    List<FlowerOutorderinfoD> list = flowerOutorderinfoDService.list(lambdaQueryWrapper);
                    String houseAll ="";
                    for(FlowerOutorderinfoD flowerOutorderinfoD :list){
                        String storehouse = flowerOutorderinfoD.getStorehouse();
                        LambdaQueryWrapper<FlowerStorehouse> houseWrapper1 = new LambdaQueryWrapper<>();
                        houseWrapper1.eq(FlowerStorehouse::getCode, storehouse);
                        FlowerStorehouse one = flowerStorehouseService.getOne(houseWrapper1);
                        houseAll = houseAll + one.getName();
                    }
                    flowerOutorderinfo.setStorehouse(houseAll );
                }
            }
            vo.setFlowerOutorderinfoList(flowerOutorderinfoList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "出库单");
        mv.addObject(NormalExcelConstants.CLASS, FlowerOutorderPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出库单数据", "导出人:" + sysUser.getRealname(), "出库单"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<FlowerOutorderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), FlowerOutorderPage.class, params);
                for (FlowerOutorderPage page : list) {
                    FlowerOutorder po = new FlowerOutorder();
                    BeanUtils.copyProperties(page, po);
                    flowerOutorderService.saveMain(po, page.getFlowerOutorderinfoList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }



    /**
     * 判断出库主表的是否在台账中真实出库
     *
     * @param id
     * @return
     */
    public boolean isMainOut(String id) {
        //查入库台账表
        List<FlowerTagInfo> taginfoList = flowerOutorderService.getTaginfoByOutoerderID(id);
        for (FlowerTagInfo tagInfo : taginfoList) {
            if (!"2".equals(tagInfo.getState())) {
                return false;
            }
        }
        return true;
    }


    /**
     * 根据品种编码/规格/长度---获取库存数量-
     *
     * @param varietyCode
     * @param packingSpecifications
     * @param flowerPoleLength
     * @return
     */
    @ApiOperation(value = "根据品种编码/规格/长度---获取库存数量-", notes = "根据品种编码---获取库存数量-(品种编码varietyCode , 打包规格packingSpecifications ,花杆长度flowerPoleLength )")
    @GetMapping(value = "/getNumsByVerityCode")
    public Result<?> getNumsByVerityCode(@RequestParam(name = "varietyCode", required = true) String varietyCode,
                                         @RequestParam(name = "packingSpecifications", required = true) String packingSpecifications,
                                         @RequestParam(name = "flowerPoleLength", required = true) String flowerPoleLength) {
        LambdaQueryWrapper<FlowerTagInfo> tagInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tagInfoLambdaQueryWrapper.eq(FlowerTagInfo::getVarietyCode, varietyCode);
        tagInfoLambdaQueryWrapper.eq(FlowerTagInfo::getPackingSpecifications, packingSpecifications);
        tagInfoLambdaQueryWrapper.eq(FlowerTagInfo::getFlowerPoleLength, flowerPoleLength);
        tagInfoLambdaQueryWrapper.eq(FlowerTagInfo::getState, 1);
        long count = flowerTagInfoService.count(tagInfoLambdaQueryWrapper);
        return Result.ok(count);
    }

    @ApiOperation(value = "弹窗查询品种编码/规格/长度...", notes = "弹窗查询品种编码/规格/长度...-(品种编码varietyCode , 打包规格packingSpecifications ,花杆长度flowerPoleLength )")
    @GetMapping(value = "/getFlowerVarietys")
    public Result<?> getFlowerVarietys(FlowerTagInfo flowerTagInfo,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                       HttpServletRequest req) {
//        QueryWrapper<FlowerTagInfo> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagInfo, req.getParameterMap());
        Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(pageNo, pageSize);
        LambdaQueryWrapper<FlowerTagInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(flowerTagInfo.getSourceBase())) {
            queryWrapper.like(FlowerTagInfo::getSourceBase, flowerTagInfo.getSourceBase());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getSourceGreenhouse())) {
            queryWrapper.eq(FlowerTagInfo::getSourceGreenhouse, flowerTagInfo.getSourceGreenhouse());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getVariety())) {
            queryWrapper.like(FlowerTagInfo::getVariety, flowerTagInfo.getVariety());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getVarietyCode())) {
            queryWrapper.eq(FlowerTagInfo::getVarietyCode, flowerTagInfo.getVarietyCode());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getPackingSpecifications())) {
            queryWrapper.eq(FlowerTagInfo::getPackingSpecifications, flowerTagInfo.getPackingSpecifications());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getFlowerPoleLength())) {
            queryWrapper.eq(FlowerTagInfo::getFlowerPoleLength, flowerTagInfo.getFlowerPoleLength());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getCost())) {
            queryWrapper.eq(FlowerTagInfo::getCost, flowerTagInfo.getCost());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getStorehouse())) {
            queryWrapper.eq(FlowerTagInfo::getStorehouse, flowerTagInfo.getStorehouse());
        }
//        if(StringUtils.isNotBlank(flowerTagInfo.getClasses())){
//            queryWrapper.eq(FlowerTagInfo::getClasses,flowerTagInfo.getClasses());
//        }
        IPage<FlowerTagInfo> pageList = (IPage<FlowerTagInfo>) flowerOutorderService.getFlowerVarietys(page, queryWrapper);
        return Result.ok(pageList);
    }

    @ApiOperation(value = "弹窗查询品种编码/规格..不带仓库.带成本中心", notes = "弹窗查询品种编码/规格/长度...不带仓库.带成本中心-(品种编码varietyCode , 打包规格packingSpecifications ,花杆长度flowerPoleLength ，costname成本中心名称，，cost成本中心编码)")
    @GetMapping(value = "/getFlowerVarietys2")
    public Result<?> getFlowerVarietys2(FlowerTagInfo flowerTagInfo,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                        HttpServletRequest req) {
//        QueryWrapper<FlowerTagInfo> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagInfo, req.getParameterMap());
        Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(pageNo, pageSize);
        QueryWrapper<FlowerTagInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(flowerTagInfo.getSourceBase())) {
            queryWrapper.like("source_base", flowerTagInfo.getSourceBase());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getSourceGreenhouse())) {
            queryWrapper.eq("source_greenhouse", flowerTagInfo.getSourceGreenhouse());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getVariety())) {
            queryWrapper.like("variety", flowerTagInfo.getVariety());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getVarietyCode())) {
            queryWrapper.eq("variety_code", flowerTagInfo.getVarietyCode());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getPackingSpecifications())) {
            queryWrapper.eq("packing_specifications", flowerTagInfo.getPackingSpecifications());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getFlowerPoleLength())) {
            queryWrapper.eq("flower_pole_length", flowerTagInfo.getFlowerPoleLength());
        }
        if (StringUtils.isNotBlank(flowerTagInfo.getCost())) {
            queryWrapper.eq(" a.cost", flowerTagInfo.getCost());
        }
        IPage<FlowerTagInfo> pageList = (IPage<FlowerTagInfo>) flowerOutorderService.getFlowerVarietys2(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 导出excel  出库单
     *
     * @param request
     * @param flowerOutorderPage
     * @return
     */
    @RequestMapping(value = "/exportXlsForOut")
    public ModelAndView exportXlsForOut(HttpServletRequest request, FlowerOutorder flowerOutorderPage) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
//        TemplateExportParams params = new TemplateExportParams("C:\\Users\\Administrator\\Desktop\\muban.xlsx");
        if (StringUtils.isBlank(tempExcelOut)) {
            throw new RuntimeException("还未配置导出模板，请联系管理员配置导出模板");
        }
        TemplateExportParams params = new TemplateExportParams(tempExcelOut);


        Map<String, Object> map = new HashMap<String, Object>();
        String sellNo = flowerOutorderPage.getSealNo();
        if (StringUtils.isBlank(sellNo)) {
            sellNo = "";
        }
        map.put("sellNo", sellNo);
        map.put("orderNo", flowerOutorderPage.getOrderNo());
        map.put("user", flowerOutorderPage.getUser());
        map.put("phone", flowerOutorderPage.getPhone());
        Date stockInTime = flowerOutorderPage.getStockInTime();
        if (stockInTime == null) {
            stockInTime = new Date();
        }
        map.put("yewuyuan", flowerOutorderPage.getBusinessPerson());//业务员
        map.put("stockInTime", simpleDateFormat.format(stockInTime));
        String stockOutUser = flowerOutorderPage.getStockOutUser();
        if (StringUtils.isBlank(flowerOutorderPage.getStockOutUser())) {
            stockOutUser = "";
        }
        map.put("stockOutUser", stockOutUser);
        map.put("businessPerson", "");
        String address = "";
        if(StringUtils.isBlank(flowerOutorderPage.getAddress())){
            address="";
        }
        map.put("address", address);
        map.put("nowTime", simpleDateFormat.format(new Date()));
        List<FlowerOutorderinfo> flowerOutorderinfoList = flowerOutorderinfoService.selectByMainId(flowerOutorderPage.getId());

        if (flowerOutorderinfoList.size() == 0) {
            throw new RuntimeException("没有出库详情不能生成出库单");
        }
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        Double countPrice = Double.parseDouble("0");
//        Double countNum = Double.parseDouble("0");
        BigDecimal countNum = BigDecimal.ZERO;
        for (FlowerOutorderinfo flowerOutorderinfo : flowerOutorderinfoList) {
            Map<String, Object> lm = new HashMap<String, Object>();
            if (StringUtils.isNotBlank(flowerOutorderinfo.getStorehouse())) {
                QueryWrapper<FlowerStorehouse> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("code", flowerOutorderinfo.getStorehouse());
                FlowerStorehouse house = flowerStorehouseService.getOne(queryWrapper);
                lm.put("storehouse", house.getName());
            } else {
                //查找拆分订单
                QueryWrapper<FlowerOutorderinfoD> infoDWrapper = new QueryWrapper<>();
                infoDWrapper.eq("mainid", flowerOutorderinfo.getId());
                List<FlowerOutorderinfoD> infoD = flowerOutorderinfoDService.list(infoDWrapper);
                String storehouse = "";
                for (FlowerOutorderinfoD flowerOutorderinfoD : infoD) {
                    String storehouse1 = flowerOutorderinfoD.getStorehouse();
                    BigDecimal number = flowerOutorderinfoD.getNumber();
                    BigDecimal totalprice = flowerOutorderinfoD.getTotalprice();

                    QueryWrapper<FlowerStorehouse> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("code", storehouse1);
                    FlowerStorehouse house = flowerStorehouseService.getOne(queryWrapper2);
                    storehouse = storehouse + house.getName() + "(" + number + " | " + totalprice + ")";
                }
                lm.put("storehouse", storehouse);
            }
            lm.put("variety", flowerOutorderinfo.getVariety());
            lm.put("packingSpecifications", flowerOutorderinfo.getPackingSpecifications());
            lm.put("flowerPoleLength", flowerOutorderinfo.getFlowerPoleLength());
            lm.put("number", flowerOutorderinfo.getNumber());
            countNum = countNum.add( flowerOutorderinfo.getNumber() );
            lm.put("price", flowerOutorderinfo.getPrice());
            lm.put("totalprice", flowerOutorderinfo.getTotalprice());
            countPrice = countPrice + flowerOutorderinfo.getTotalprice().doubleValue();

            if (StringUtils.isNotBlank(flowerOutorderinfo.getCost())) {
//                Result<String> dd = sysDictServiceClient.getDictTextOpen("ch_cost",
//                        flowerOutorderinfo.getCost());
                String name = sysDictService.queryDictTextByKey("ch_cost", flowerOutorderinfo.getCost());
                lm.put("cost", name);
            } else {
                lm.put("cost", "");
            }
            listMap.add(lm);
        }
        if (flowerOutorderinfoList.size() == 1) {
            Map<String, Object> lm = new HashMap<String, Object>();
            listMap.add(lm);
        }
        map.put("countPrice", String.valueOf(countPrice));
        map.put("countNum", String.valueOf(countNum));
        map.put("maplist", listMap);

        ModelAndView mv2 = new ModelAndView(new JeecgTemplateExcelView());
        mv2.addObject(TemplateExcelConstants.PARAMS, params);
        mv2.addObject(TemplateExcelConstants.MAP_DATA, map);
        return mv2;
    }

    /**
     * 导出excel结算单
     * 需要和售后单做~~~~计算
     *
     * @param request
     * @param flowerOutorderPage
     * @return
     */
    @RequestMapping(value = "/exportXlsForAccont")
    public ModelAndView exportXlsForAccont(HttpServletRequest request, FlowerOutorder flowerOutorderPage) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
//        TemplateExportParams params = new TemplateExportParams("C:\\Users\\Administrator\\Desktop\\jiesuandan.xlsx");
        if (StringUtils.isBlank(tempExcelOrder)) {
            throw new RuntimeException("还未配置导出模板，请联系管理员配置导出模板");
        }
        TemplateExportParams params = new TemplateExportParams(tempExcelOrder);//模板

        //查找售后单
        QueryWrapper<FlowerAfSalesMain> queryWrapper = new QueryWrapper<>();
        if ( StringUtils.isNotBlank(flowerOutorderPage.getSealNo())) {
            queryWrapper.eq("order_no", flowerOutorderPage.getSealNo());
        } else {
            queryWrapper.eq("order_no", flowerOutorderPage.getOrderNo());
        }
        List<FlowerAfSalesMain> list = flowerAfSalesMainService.list(queryWrapper);
        List<FlowerAfSalesDetal> AfSalesDetallist1 = new ArrayList<>();
        if (list.size() > 0) {
            FlowerAfSalesMain flowerAfSalesMain = list.get(0);
            LambdaQueryWrapper<FlowerAfSalesDetal> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(FlowerAfSalesDetal::getMainid, flowerAfSalesMain.getId());
            AfSalesDetallist1 = flowerAfSalesDetalService.list(queryWrapper1);
        }

        Map<String, Object> map = new HashMap<String, Object>();
        String remarks = flowerOutorderPage.getRemarks();
        if (StringUtils.isBlank(remarks)) {
            remarks = "";
        }
        map.put("remarks", remarks);
        String sellNo = flowerOutorderPage.getSealNo();
        if (StringUtils.isBlank(sellNo)) {
            sellNo = "";
        }
        map.put("sellNo", sellNo);
        map.put("orderNo", flowerOutorderPage.getOrderNo());
        map.put("user", flowerOutorderPage.getUser());
        map.put("phone", flowerOutorderPage.getPhone());
        Date stockInTime = flowerOutorderPage.getStockInTime();
        if (stockInTime == null) {
            stockInTime = new Date();
        }
        map.put("stockInTime", simpleDateFormat.format(stockInTime));

        map.put("yewuyuan", flowerOutorderPage.getBusinessPerson());//业务员

        String stockOutUser = flowerOutorderPage.getStockOutUser();
        if (StringUtils.isBlank(flowerOutorderPage.getStockOutUser())) {
            stockOutUser = "";
        }
        map.put("stockOutUser", stockOutUser);

        Date surepipetime = flowerOutorderPage.getSurepipetime();
        if (surepipetime==null) {
            surepipetime = null;
        }
        map.put("surepipetime", simpleDateFormat.format(surepipetime));
        map.put("finaSureUser", flowerOutorderPage.getFinaSureUser());
        map.put("surepipeuser", flowerOutorderPage.getSurepipeuser());
        map.put("sureoutuser", flowerOutorderPage.getSureoutuser());

        String address = "";
        if(StringUtils.isNotBlank( flowerOutorderPage.getAddress())){
            address = flowerOutorderPage.getAddress();
        }
        map.put("address", address);
        map.put("nowTime", simpleDateFormat.format(new Date()));
        List<FlowerOutorderinfo> flowerOutorderinfoList = flowerOutorderinfoService.selectByMainId(flowerOutorderPage.getId());

        if (flowerOutorderinfoList.size() == 0) {
            throw new RuntimeException("没有出库详情不能生成结算单");
        }
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        BigDecimal countPrice = BigDecimal.ZERO;
        BigDecimal countNum =  BigDecimal.ZERO;

        for (FlowerOutorderinfo flowerOutorderinfo : flowerOutorderinfoList) {
            Map<String, Object> lm = new HashMap<String, Object>();
            if (StringUtils.isNotBlank(flowerOutorderinfo.getStorehouse())) {
                QueryWrapper<FlowerStorehouse> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("code", flowerOutorderinfo.getStorehouse());
                FlowerStorehouse house = flowerStorehouseService.getOne(queryWrapper2);
                lm.put("storehouse", house.getName());
            } else {
                //查找拆分订单
                QueryWrapper<FlowerOutorderinfoD> infoDWrapper = new QueryWrapper<>();
                infoDWrapper.eq("mainid", flowerOutorderinfo.getId());
                List<FlowerOutorderinfoD> infoD = flowerOutorderinfoDService.list(infoDWrapper);
                String storehouse = "";
                for (FlowerOutorderinfoD flowerOutorderinfoD : infoD) {
                    String storehouse1 = flowerOutorderinfoD.getStorehouse();
                    BigDecimal number = flowerOutorderinfoD.getNumber();
                    BigDecimal totalprice = flowerOutorderinfoD.getTotalprice();

                    QueryWrapper<FlowerStorehouse> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("code", storehouse1);
                    FlowerStorehouse house = flowerStorehouseService.getOne(queryWrapper2);
                    storehouse = storehouse + house.getName() + "(" + number + " | " + totalprice + ")";
                }
                lm.put("storehouse", storehouse);
            }
            lm.put("variety", flowerOutorderinfo.getVariety());
            lm.put("packingSpecifications", flowerOutorderinfo.getPackingSpecifications());
            lm.put("flowerPoleLength", flowerOutorderinfo.getFlowerPoleLength());

            BigDecimal totalprice1 = flowerOutorderinfo.getTotalprice();
            BigDecimal number = flowerOutorderinfo.getNumber();
            BigDecimal pnumber =  number ;
//            Double pnumber = Double.parseDouble(number);
            if (AfSalesDetallist1.size() > 0) {
                for (FlowerAfSalesDetal flowerAfSalesDetal : AfSalesDetallist1) {
                    if (flowerAfSalesDetal.getVarietyCode().equals(flowerOutorderinfo.getVarietyCode())) {
                        BigDecimal afNumber = flowerAfSalesDetal.getNumber();
                        BigDecimal afSealPrice = flowerAfSalesDetal.getAfSealPrice();//售后价格
                        if (afNumber == null  ) {
                            afNumber = BigDecimal.ZERO;
                        }
                        pnumber = number .subtract( afNumber);
                        totalprice1 = totalprice1.subtract(afSealPrice);//总价减去收货价格
                        break;
                    }
                }
            }
            lm.put("number", pnumber);
            countNum =countNum.add( pnumber);//计算数量合计

            BigDecimal price = flowerOutorderinfo.getPrice();
            lm.put("price", flowerOutorderinfo.getPrice());

//            Double totalprice  =  Double.parseDouble("0");
//            BigDecimal totalprice  =  flowerOutorderinfo.getTotalprice();
//            totalprice =   pnumber *  (price.doubleValue());

            lm.put("totalprice", totalprice1);
            countPrice = countPrice.add( totalprice1);//计算合计
            listMap.add(lm);
        }
        if (flowerOutorderinfoList.size() == 1) {
            Map<String, Object> lm = new HashMap<String, Object>();
            listMap.add(lm);
        }
        BigDecimal countPrice22 =  countPrice ;
        map.put("countPrice", countPrice22.setScale(2, BigDecimal.ROUND_HALF_UP));
        map.put("countNum", countNum);
        map.put("maplist", listMap);

        ModelAndView mv2 = new ModelAndView(new JeecgTemplateExcelView());
        mv2.addObject(TemplateExcelConstants.PARAMS, params);
        mv2.addObject(TemplateExcelConstants.MAP_DATA, map);
        return mv2;
    }

    /**
     * 出库汇总接口
     *
     * @param storehouse
     * @param cost
     * @param pageNo
     * @param pageSize
     * @param sDate
     * @param eDate
     * @param req
     * @return
     */
    @AutoLog(value = "出库汇总接口-分页列表查询")
    @ApiOperation(value = "出库汇总接口-分页列表查询", notes = "出库汇总-分页列表查询")
    @GetMapping(value = "/huiZonglist")
    public Result<?> huiZonglist(@RequestParam(value = "storehouse", defaultValue = "") String storehouse,
                                 @RequestParam(value = "cost", defaultValue = "") String cost,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 @RequestParam(value = "sDate", defaultValue = "") String sDate,
                                 @RequestParam(value = "eDate", defaultValue = "") String eDate,
                                 HttpServletRequest req) {

//        QueryWrapper<FlowerAcont> queryWrapper = QueryGenerator.initQueryWrapper(flowerAcont, req.getParameterMap());
        QueryWrapper<FlowerAcont> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(storehouse)) {
            queryWrapper.eq("bb.storehouse", storehouse);
        }
        if (StringUtils.isNotBlank(cost)) {
            queryWrapper.eq("bb.cost", cost);
        }

        Page<FlowerAcont> page = new Page<FlowerAcont>(pageNo, pageSize);
        IPage<FlowerAcont> pageList = flowerCostService.huiZonglist(page, queryWrapper, sDate, eDate + " 23:59:59");
        return Result.ok(pageList);
    }


    @GetMapping(value = "/huiZonglistExport")
    public ModelAndView huiZonglistExport(@RequestParam(value = "storehouse", defaultValue = "") String storehouse,
                                          @RequestParam(value = "cost", defaultValue = "") String cost,
                                          @RequestParam(value = "sDate", defaultValue = "") String sDate,
                                          @RequestParam(value = "eDate", defaultValue = "") String eDate
    ) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        // Step.1 组装查询条件查询数据
        QueryWrapper<FlowerAcont> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(storehouse)) {
            queryWrapper.eq("bb.storehouse", storehouse);
        }
        if (StringUtils.isNotBlank(cost)) {
            queryWrapper.eq("bb.cost", cost);
        }
        Page<FlowerAcont> page = new Page<FlowerAcont>(1, 99999999);
        IPage<FlowerAcont> pageList = flowerCostService.huiZonglist(page, queryWrapper, sDate, eDate + " 23:59:59");

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "出库汇总接口");
        mv.addObject(NormalExcelConstants.CLASS, FlowerAcont.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出库汇总接口", "导出人:" + sysUser.getRealname(), "出库单主表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList.getRecords());
        return mv;
    }

    @ApiOperation(value = "出库管理-基地负责人审核 ", notes = "出库管理-基地负责人审核 ")
    @GetMapping(value = "/fiunalSure")
    public  Result<?> fiunalSure(@RequestParam(value = "id") String id) throws IOException {
        String result = "操作失败";
        synchronized (id) {
            result = flowerOutorderService.fiunalSure(id);
        }
        return Result.ok(result);
    }



    @ApiOperation(value = "撤销 基地负责人审核 ", notes = "出库管理-撤销基地负责人审核 ")
    @GetMapping(value = "/fiunalSureBack")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> fiunalSureBack(@RequestParam(value = "id") String id) throws IOException {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        FlowerOutorder outoer = flowerOutorderService.getById(id);
        if (outoer.getState() == 3) {
            return Result.ok("您已经撤销过了成功");
        }
        if (outoer.getState() != 1) {
            return Result.ok("请先进行【运管审核】");
        }

        FlowerOutorder flowerOutorder = new FlowerOutorder();
        flowerOutorder.setId(id);
        flowerOutorder.setFinaSureUser("");
        flowerOutorder.setFinaSureTime(null);
        flowerOutorder.setTopresstime(outoer.getTopresstime() );
        flowerOutorder.setState( 3 ); //状态改为 -1已提交审核
        boolean b = flowerOutorderService.updateById(flowerOutorder);

        FlowerOutorder flowerOutorderOld  = flowerOutorderService.getById(id);

        QueryWrapper<FlowerOutorderinfo> queryWrapper =new QueryWrapper<>();
        queryWrapper.select( "sum( totalprice) as totalprice" );
        queryWrapper.eq( "order_id" , id);
        FlowerOutorderinfo flowerOutorderinfo = flowerOutorderinfoService.getOne(queryWrapper);

        if (b) {
            return Result.ok("撤销基地负责人审核成功");
        } else {
            return Result.error("撤销基地负责人审核失败");
        }
    }

    @AutoLog(value = "提交审核----")
    @ApiOperation(value = "提交审核----", notes = "提交审核 ")
    @GetMapping(value = "/toPress")
    public  Result<?> toPress(@RequestParam(name = "id", required = true) String id) throws IOException {
        int outDo = 0;

        synchronized (CommonUtil.SUBTAGINFOKEY){
            outDo = flowerOutorderService.toPress(id);
        }
        return Result.ok("提交审核成功!扣减总库存数：" + outDo );
    }
    //提交审核-撤销
    @ApiOperation(value = "提交审核-- -撤销", notes = " -提交审核 -撤销")
    @GetMapping(value = "/toPressBack")
    public  Result<?> toPressBack(@RequestParam(value = "id") String id) throws IOException {
        synchronized(CommonUtil.SUBTAGINFOKEY) {
            flowerOutorderService.toPressBack(id);
        }
        return Result.ok("撤销审核成功");
    }
    /**
     * 确认出库
     *
     * @param id string[]
     * @return
     */
    @AutoLog(value = "确认出库----")
    @ApiOperation(value = "库管确认出库----", notes = "库管确认出库 ")
    @GetMapping(value = "/sureOut")
    public  Result<?> sureOut(@RequestParam(name = "id", required = true) String id) throws IOException {
        synchronized(CommonUtil.SUBTAGINFOKEY) {
            flowerOutorderService.sureOutDo(id);
        }
        return Result.ok("确认出库成功"  );
    }


    /**
     * 返回到待出库
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单表-撤销库管确认出库")
    @ApiOperation(value = "出库单表-撤销库管确认出库", notes = "出库单表-撤销库管确认出库")
    @GetMapping(value = "/toWaitOut")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> toWaitOut(@RequestParam(name = "id", required = true) String id) throws IOException {
        synchronized(CommonUtil.SUBTAGINFOKEY) {
            flowerOutorderService.sureOutDoBack(id);
        }

        return Result.ok("撤销成功!");
    }



    //运管备案
    @ApiOperation(value = "运管备案-- ", notes = " -运管备案- ")
    @PutMapping(value = "/transportPipe")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> transportPipe(@RequestBody FlowerOutorderPage flowerOutorderPage) throws IOException {
        String id=flowerOutorderPage.getId();

        FlowerOutorder flowerOutorder = new FlowerOutorder();
        BeanUtils.copyProperties(flowerOutorderPage, flowerOutorder);
        Integer state = flowerOutorder.getState();
        if(state == 2){
            throw new RuntimeException("已经【运管备案】过了");
        }
        if(state != 1){
            throw new RuntimeException("请先进行【基地负责人审核】");
        }
        //将运管写的备注更新进主表。--售后信息
        String remarks = flowerOutorder.getRemarks();
        BigDecimal sumNum = BigDecimal.ZERO ;
        BigDecimal sumTotalprice = BigDecimal.ZERO ;
        for( FlowerOutorderinfo flowerOutorderinfo2 :flowerOutorderPage.getFlowerOutorderinfoList()){
            sumNum= sumNum.add(flowerOutorderinfo2.getNumber() );
            sumTotalprice  =  sumTotalprice.add( flowerOutorderinfo2.getTotalprice())  ;
        }
        flowerOutorderService.transportPipe(id, remarks, sumNum , sumTotalprice);
        return Result.ok("运管备案成功");
    }
    //撤销运管确认
    @ApiOperation(value = "撤销运管备案-- ", notes = " -撤销运管备案 ")
    @GetMapping(value = "/transportPipeBack")
    public  Result<?> transportPipeBack(@RequestParam(value = "id") String id) throws IOException {
        synchronized(id) {
            flowerOutorderService.transportPipeBack(id);
        }
        return Result.ok("撤销运管确认成功");
    }



    //结算确认
    @ApiOperation(value = "结算确认-- ", notes = " -结算确认- ")
    @GetMapping(value = "/accountSure")
    public Result<?> accountSure(@RequestParam(value = "id") String id ) throws IOException {
        synchronized(id) {
            FlowerOutorder flowerOutorder = flowerOutorderService.getById(id);
            Integer state = flowerOutorder.getState();
            if (state == 4) {
                throw new RuntimeException("已经【结算确认】过了");
            }
            if (state != 0) {
                throw new RuntimeException("请先进行【库管确认出库】");
            }
            flowerOutorderService.accountSure(flowerOutorder);
        }
        return Result.ok("结算确认成功");
    }
    //撤销运管确认
    @ApiOperation(value = "撤销结算确认-- ", notes = " -撤销结算确认 ")
    @GetMapping(value = "/accountSureBack")
    public  Result<?> accountSureBack(@RequestParam(value = "id") String id) throws IOException {
        synchronized(id) {
            flowerOutorderService.accountSureBack(id);
        }
        return Result.ok("撤销运结算确认成功");
    }


}
